<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 9:39
 */

namespace app\index\controller;


use app\api\model\Common;
use app\api\model\schemeMaster;
use think\Db;
use think\Request;
use think\Exception;
use think\Cache;

class Scheme extends Backend
{

    public function index()
    {
        $data = Request::instance()->get();
        $schemeMaster = new  schemeMaster();
        $rows = $schemeMaster
            ->join('city', 'city.city_id=scheme_master.city_id', 'left')
            ->join('county', 'county.county_id=scheme_master.area', 'left')
            ->join('user', 'user.user_id=scheme_master.user_id', 'left');


        if (isset($data['name']) && $data['name'] != '') {
            $rows->where(['scheme_master.name' => ['like', "%{$data['name']}%"]]);
        }

        if (isset($data['start_time']) && $data['start_time'] != '' && isset($data['end_time']) && $data['end_time'] != '') {

            $rows->whereBetween('scheme_master.creation_time', [strtotime($data['start_time']), strtotime($data['end_time']) + 24 * 3600]);
        }
        if (isset($data['state']) && $data['state'] != '') {

            $rows->where('scheme_master.state', $data['state']);
        }
        if (isset($data['user_id']) && $data['user_id'] != '') {

            $rows->where(['user.username' => ['like', "%{$data['user_id']}%"]]);
        }
        if (isset($data['HouseData']) && $data['HouseData'] != '') {
            if ($data['HouseData'] == 9) {
                $schemeHouse = db('scheme_house', config('database.zong'))->group('plan_id')->column('plan_id');
            } else {
                $schemeHouse = db('scheme_house', config('database.zong'))->where('house', $data['HouseData'])->group('plan_id')->column('plan_id');
            }
            if (!empty($schemeHouse)) {
                $rows->whereIn('scheme_master.plan_id', $schemeHouse);
            }
        }
        if (isset($data['category']) && $data['category'] != '') {
            $scheme_category = db('scheme_category', config('database.zong'))->whereIn('category_id', $data['category'])->group('plan_id');
            $scheme_category = $scheme_category->column('plan_id');
            if (!empty($scheme_category)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_category);
            }

        }
//        $data = $rows->field('scheme_master.*,FROM_UNIXTIME(scheme_master.creation_time) as creationTime,city.city,county.county,user.username')->group('plan_id')->fetchSql()->select();
//        var_dump($data);die;

        $data = $rows->field('scheme_master.*,FROM_UNIXTIME(scheme_master.creation_time) as creationTime,city.city,county.county,user.username')->group('plan_id')
            ->order('scheme_master.plan_id desc')->where('scheme_master.type', 1)->paginate(20)->each(function ($item, $key) use ($schemeMaster) {
                if ($item['state'] == 1) {
                    $item['states'] = "启用";
                } else {
                    $item['states'] = '禁用';
                }
                if ($item['private'] == 1) {
                    $item['privates'] = "所有";
                } else {
                    $item['privates'] = '个人';
                }
                $item['username'] = empty($item['username']) ? '' : $item['username'];
                $item['Community'] = implode(',', $schemeMaster->schemeCommunity()->where('plan_id', $item['plan_id'])->column('name'));
                $item['House'] = implode(',', $schemeMaster->schemeHouse()->where('plan_id', $item['plan_id'])->column('name'));
                $item['schemeCategory'] = implode(',', $schemeMaster->schemeCategory()->where('plan_id', $item['plan_id'])->column('category_name'));
                $item['schemeUse'] = $schemeMaster->schemeUse()->where('plan_id', $item['plan_id'])->count('id');;
                return $item;

            });

        $common = new Common();
        $HouseData = $common->HouseData();
        $res = db('goods_category')->field('goods_category.title,goods_category.id')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => 0, 'type' => 1])->select();
        return $this->fetch('index', ['data' => $data, 'HouseData' => $HouseData, 'goods_category' => $res]);
    }

    /**
     * @return array|mixed|string
     * 添加短信
     */
    public function add($id)
    {
        if ($parameter = Request::instance()->post()) {

            Db::connect(config('database.zong'))->startTrans();
            try {
                $project = json_decode($parameter['dataList'], true);
                $schemeLabel = Db::connect(config('database.zong'))->table('scheme_master')->insertGetId([
                    'name' => $parameter['store_name'],
                    'info' => $parameter['info'],
                    'day' => $parameter['day'],
                    'creation_time' => time(),
                    'user_id' => 0,
                    'private' => 1,
                    'city_id' => $parameter['cityid'],
                    'area' => $parameter['area'],
                    'scheme_no' => 'YNWX' . date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                ]);
                //方案大师项目添加
                foreach ($project as $item) {
                    Db::connect(config('database.zong'))->table('scheme_project')->insert([
                        'plan_id' => $schemeLabel,
                        'projectId' => $item['projectId'],
                        'projectMoney' => $item['un_Price'],
                        'projectTitle' => $item['class_b'],
                        'category' => $item['chan'],
                        'company' => $item['company'],
                        'agency' => $item['agency'],
                        'to_price' => sprintf('%.2f', $item['square'] * $item['un_Price']),
                        'square' => $item['square'],
                        'remarks' => isset($item['remarks']) ? $item['remarks'] : '',
                    ]);
                }
                //方案大师图片添加
                if (isset($parameter['img'])) {
                    foreach ($parameter['img'] as $item) {
                        Db::connect(config('database.zong'))->table('scheme_img')->insertGetId([
                            'plan_id' => $schemeLabel,
                            'title' => $item['title'],
                            'path' => $item['logo'],
                        ]);
                    }
                }


                foreach ($parameter['scheme_community'] as $item) {
                    if(!empty($item)){
                        $houseData = Db::connect(config('database.zong'))->table('house')->where('id', $item)->field('area,name')->find();
                    }

                    Db::connect(config('database.zong'))->table('scheme_community')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'community' => $item,
                        'name' => empty($item)?'全部':$houseData['name'],
                        'area' =>  empty($item)?0:$houseData['area'],
                    ]);

                }

                foreach ($parameter['house'] as $item) {
                    $house = explode(',', $item);
                    Db::connect(config('database.zong'))->table('scheme_house')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'house' => $house[0],
                        'name' => $house[1],
                    ]);


                }

                foreach ($parameter['labelListarray'] as $item) {
                    if (isset($item['biaoti'])) {
                        foreach ($item['biaoti'] as $value) {

                            Db::connect(config('database.zong'))->table('scheme_tag')->insertGetId([
                                'plan_id' => $schemeLabel,
                                'tag' => $value['id'],
                                'name' => Db::connect(config('database.zong'))->table('scheme_label')->where('id', $value['id'])->value('title'),
                                'type' => 1,
                                'pid' => $item['id'],
                            ]);
                        }
                    }
                    if (isset($item['wenti'])) {
                        foreach ($item['wenti'] as $value) {
                            Db::connect(config('database.zong'))->table('scheme_tag')->insertGetId([
                                'plan_id' => $schemeLabel,
                                'tag' => $value['id'],
                                'name' => Db::connect(config('database.zong'))->table('scheme_label')->where('id', $value['id'])->value('title'),
                                'type' => 2,
                                'pid' => $item['id'],
                            ]);
                        }
                    }

                }
                foreach ($parameter['scheme_category'] as $item) {

                    $scheme_category = explode(',', $item);
                    Db::connect(config('database.zong'))->table('scheme_category')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'category_id' => $scheme_category[0],
                        'category_name' => $scheme_category[1],
                    ]);
                }
                Db::connect(config('database.zong'))->commit();
                return json_data($schemeLabel, 200);
            } catch (Exception $exception) {
                Db::connect(config('database.zong'))->rollback();
                return json_data(null, 300, $exception->getMessage());
            }
        }
        $common = new Common();
        $res =  db('scheme_label_top', config('database.zong'))->field('id,title')->whereNull('delete_time')->select();
        $HouseData = $common->HouseData();


        $go = db('goods_category')->where(['pro_type' => 1, 'parent_id' => 0])->select();
        $gs = db('product_chan')->where(['pro_types' => 1, 'parents_id' => 0])->select();
        $po = db('detailed')->where(['detaileds_id' => 0])->select();
        $g = db('unit')->select();

        return $this->fetch('add', ['goods_category' => $res, 'HouseData' => $HouseData, 'labelList' => [], 'id' => empty($id) ? time() : $id, 'go' => $go, 'g' => $g, 'gs' => $gs, 'po' => $po]);
    }

    /*
        * 获取小区
        */
    public function quartersList()
    {
        $city = Request::instance()->post();

        if (Cache::get($city['city'] . 'city' . $city['area'] . 'area')) {
            $list = Cache::get($city['city'] . 'city' . $city['area'] . 'area');
        } else {
            $list = \db('house', config('database.zong'))->where('city', $city['city'])->where('area', $city['area'])->field('id,name,city as cityId,area')->select();
            Cache::set($city['city'] . 'city' . $city['area'] . 'area', $list);
        }
        $data=[
            [
                'id'=>0,
                'name'=>'全部',
                'area'=>0,
            ]

        ];
        $list=array_merge($data,$list);
        return $list;
    }


    /**
     * @return array|mixed|string
     * 编辑短信
     */
    public function edit($id = 0)
    {
        if ($parameter = Request::instance()->post()) {
          // var_dump(json_encode($parameter));die;
            Db::connect(config('database.zong'))->startTrans();
            try {
                $project = json_decode($parameter['dataList'], true);
                Db::connect(config('database.zong'))->table('scheme_master')->where('plan_id', $parameter['schemeId'])->update([
                    'name' => $parameter['store_name'],
                    'info' => $parameter['info'],
                    'day' => $parameter['day'],
                    'city_id' => $parameter['cityid'],
                    'area' => $parameter['area'],
                ]);
                Db::connect(config('database.zong'))->table('scheme_project')->where('plan_id', $parameter['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_img')->where('plan_id', $parameter['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_community')->where('plan_id', $parameter['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_house')->where('plan_id', $parameter['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_tag')->where('plan_id', $parameter['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_category')->where('plan_id', $parameter['schemeId'])->delete();
                $schemeLabel = $parameter['schemeId'];
                //方案大师项目添加
                foreach ($project as $item) {
                    Db::connect(config('database.zong'))->table('scheme_project')->insert([
                        'plan_id' => $schemeLabel,
                        'projectId' => $item['projectId'],
                        'projectMoney' => $item['un_Price'],
                        'projectTitle' => $item['class_b'],
                        'category' => $item['chan'],
                        'company' => $item['company'],
                        'agency' => $item['agency'],
                        'to_price' => sprintf('%.2f', $item['square'] * $item['un_Price']),
                        'square' => $item['square'],
                        'remarks' => isset($item['remarks']) ? $item['remarks'] : '',
                    ]);
                }
                //方案大师图片添加
                if (isset($parameter['img'])) {
                    foreach ($parameter['img'] as $item) {
                        Db::connect(config('database.zong'))->table('scheme_img')->insertGetId([
                            'plan_id' => $schemeLabel,
                            'title' => $item['title'],
                            'path' => $item['logo'],
                        ]);
                    }
                }

                foreach ($parameter['scheme_community'] as $item) {
                    if(!empty($item)){
                        $houseData = Db::connect(config('database.zong'))->table('house')->where('id', $item)->field('area,name')->find();
                    }

                    Db::connect(config('database.zong'))->table('scheme_community')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'community' => $item,
                        'name' => empty($item)?'全部':$houseData['name'],
                        'area' =>  empty($item)?0:$houseData['area'],
                    ]);

                }

                foreach ($parameter['house'] as $item) {
                    $house = explode(',', $item);
                    Db::connect(config('database.zong'))->table('scheme_house')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'house' => $house[0],
                        'name' => $house[1],
                    ]);


                }

                foreach ($parameter['labelListarray'] as $item) {
                    if (isset($item['biaoti'])) {
                        foreach ($item['biaoti'] as $value) {

                            Db::connect(config('database.zong'))->table('scheme_tag')->insertGetId([
                                'plan_id' => $schemeLabel,
                                'tag' => $value['id'],
                                'name' => Db::connect(config('database.zong'))->table('scheme_label')->where('id', $value['id'])->value('title'),
                                'type' => 1,
                                'pid' => $item['id'],
                            ]);
                        }
                    }
                    if (isset($item['wenti'])) {
                        foreach ($item['wenti'] as $value) {
                            Db::connect(config('database.zong'))->table('scheme_tag')->insertGetId([
                                'plan_id' => $schemeLabel,
                                'tag' => $value['id'],
                                'name' => Db::connect(config('database.zong'))->table('scheme_label')->where('id', $value['id'])->value('title'),
                                'type' => 2,
                                'pid' => $item['id'],
                            ]);
                        }
                    }

                }
                foreach ($parameter['scheme_category'] as $item) {

                    $scheme_category = explode(',', $item);
                    Db::connect(config('database.zong'))->table('scheme_category')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'category_id' => $scheme_category[0],
                        'category_name' => $scheme_category[1],
                    ]);
                }
                Db::connect(config('database.zong'))->commit();
                return json_data($schemeLabel, 200);
            } catch (Exception $exception) {
                Db::connect(config('database.zong'))->rollback();
                return json_data(null, 300, $exception->getMessage());
            }
        }

        if (!$id) {
            $this->error('请刷新后重试');
        }
        $schemeMaster = new schemeMaster();
        $res = $schemeMaster->with('schemeProject')
            ->with('schemeProject')
            ->with('schemeImg')
            ->with('schemeCommunity')
            ->with('schemeHouse')
            ->with('city')
            ->with('county')
            ->with('user')
            ->with('schemeTag')
            ->with('SchemeCollection')
            ->with('schemeCategory')
            ->where('scheme_master.plan_id', $id)
            ->find()->toArray();

        $common = new Common();
        $goods_category = db('scheme_label_top', config('database.zong'))->field('id,title')->whereNull('delete_time')->select();;
        foreach ($res['scheme_category'] as $i) {
            foreach ($goods_category as $k => $item) {

                if ($i['category_id'] == $item['id']) {
                    $goods_category[$k]['select'] = 1;
                }
            }

        }
        $HouseData = $common->HouseData();
        foreach ($res['scheme_house'] as $i) {

            foreach ($HouseData as $k => $datum) {
                if ($datum['id'] == $i['house']) {
                    $HouseData[$k]['select'] = 1;
                }

            }
        }
        $labelList = db('scheme_label_top', config('database.zong'))->field('id,title')->whereIn('id',array_column($res['scheme_category'],'category_id'))->select();

        $schemeLabel = db('scheme_label', config('database.zong'))->field('id,title,pid,classification')->whereNull('delete_time')->select();
        foreach ($labelList as $k => $value) {
            foreach ($schemeLabel as $j => $l) {
                if ($value['id'] == $l['pid']) {
                    if ($l['classification'] == 1) {
                        $labelList[$k]['position'][] = $l;
                        foreach ($labelList[$k]['position'] as $p => $item) {
                            foreach ($res['scheme_tag'] as $i) {
                                if ($value['id'] == $i['pid'] && $i['type'] == 1) {
                                    if ($i['tag'] == $item['id']) {
                                        $labelList[$k]['position'][$p]['select'] = 1;
                                    }

                                }
                            }

                            unset($labelList[$k]['position'][$p]['pid'], $labelList[$k]['position'][$p]['classification']);
                        }
                    }
                    if ($l['classification'] == 2) {
                        $labelList[$k]['problem'][] = $l;
                        foreach ($labelList[$k]['problem'] as $p => $item) {
                            foreach ($res['scheme_tag'] as $i) {
                                if ($value['id'] == $i['pid'] && $i['type'] == 2) {
                                    if ($i['tag'] == $item['id']) {
                                        $labelList[$k]['problem'][$p]['select'] = 1;
                                    }

                                }
                            }
                            unset($labelList[$k]['problem'][$p]['pid'], $labelList[$k]['problem'][$p]['classification']);
                        }
                    }
                }
            }
        }

        $go = db('goods_category')->where(['pro_type' => 1, 'parent_id' => 0])->select();
        $gs = db('product_chan')->where(['pro_types' => 1, 'parents_id' => 0])->select();
        $po = db('detailed')->where(['detaileds_id' => 0])->select();
        $g = db('unit')->select();

        return $this->fetch('edit', ['data' => $res, 'goods_category' => $goods_category, 'HouseData' => $HouseData, 'labelList' => $labelList, 'id' => empty($id) ? time() : $id, 'go' => $go, 'g' => $g, 'gs' => $gs, 'po' => $po, 'community' => json_encode($res["scheme_community"]), 'scheme_project' => json_encode($res["scheme_project"])]);
    }


    public function del()
    {
        $id = Request::instance()->post();
        if ($id) {
            $res = db('scheme_master', config('database.zong'))->where(['plan_id' => $id['id']])->update(['state' => $id['msg']]);
            if ($res !== false) {
                return json_data([], 200, '操作成功');
            }
        }

        return json_data([], 300, '操作失败');
    }

    public function schemeLabeltop()
    {
        $id = Request::instance()->post();
        $labelList = db('scheme_label_top', config('database.zong'))->field('id,title')->whereNull('delete_time')->whereIn('id', $id['param1'])->select();
        $schemeLabel = db('scheme_label', config('database.zong'))->field('id,title,pid,classification')->whereNull('delete_time')->select();
        foreach ($labelList as $k => $value) {
            foreach ($schemeLabel as $j => $l) {
                if ($value['id'] == $l['pid']) {
                    if ($l['classification'] == 1) {
                        $labelList[$k]['position'][] = $l;
                        foreach ($labelList[$k]['position'] as $p => $item) {
                            unset($labelList[$k]['position'][$p]['pid'], $labelList[$k]['position'][$p]['classification']);
                        }
                    }
                    if ($l['classification'] == 2) {
                        $labelList[$k]['problem'][] = $l;
                        foreach ($labelList[$k]['problem'] as $p => $item) {
                            unset($labelList[$k]['problem'][$p]['pid'], $labelList[$k]['problem'][$p]['classification']);
                        }
                    }
                }
            }
        }
        return $labelList;
    }

    public function info($id = 0)
    {
        $schemeMaster = new schemeMaster();
        $rows = $schemeMaster->with('schemeProject')
            ->with('schemeProject')
            ->with('schemeImg')
            ->with('schemeCommunity')
            ->with('schemeHouse')
            ->with('city')
            ->with('county')
            ->with('user')
            ->with('schemeTag')
            ->with('SchemeCollection')
            ->with('schemeCategory')
            ->where('scheme_master.plan_id', $id)
            ->find()->toArray();

        $tageList = [];
        if ($rows['scheme_tag']) {
            $result = array();
            foreach ($rows['scheme_tag'] as $k => $v) {
                $result[$v['pid']][] = $v;
            }

            foreach ($result as $k => $list) {
                $schemeTag['id'] = $k;

                $schemeTag['position'] = $result[$k];
                unset($rows['scheme_tag']);
                $tageList[] = $schemeTag;
            }
            foreach ($tageList as $k => $list) {
               
                $tageList[$k]['title'] = db('scheme_label_top', config('database.zong'))->field('id,title')->where('id', $list['id'])->value('title');
            }
        }
        foreach ($rows['scheme_community'] as $k => $v) {
            $rows['scheme_community'][$k]['cityId'] = $rows['city_id'];
            $rows['scheme_community'][$k]['area'] = $rows['area'];
        }
        $rows['scheme_tag'] = $tageList;
        $rows['creation_time'] = date('Y-m-d H:i:s', $rows['creation_time']);
        $rows['address'] = $rows['city']['city'] . '-' . $rows['county']['county'];
        $rows['offer'] = array_sum(array_column($rows['scheme_project'], 'to_price'));
        $rows['briefIntroduction'] = empty($rows['user']['username'])?'':$rows['scheme_house'][0]['name'] . '|' . $rows['user']['username'];
        $rows['collection'] = empty($rows['scheme_collection']) ? 0 : 1;

        return $this->fetch('info', ['data' => $rows]);
    }


}
